Page({
  data: {
    isAdmin: false,
    loadModal: false,
    date: '',
    show: false,
    minDate: new Date().getTime() - 24 * 60 * 60 * 1000 * 60,
    maxDate: new Date().getTime()
  },
  onLoad() {
    this.loadModal()
    wx.cloud.callFunction({
        name: 'adminAuth'
      })
      .then(res => {
        console.log('adminAuth', res.result)
        if (res.result) {
          this.setData({
            isAdmin: true,
            loadModal: false
          })
        } else {
          this.setData({
            loadModal: false
          })
          wx.reLaunch({
            url: '/pages/index/index'
          })
        }
      })
  },
  sendColumnPreviewMessage() {
    var that = this
    wx.showModal({
      confirmColor: 'red',
      title: '提示',
      content: '是否确认群发，无法撤回！',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          var date = that.dateFormat("YYYY-mm-dd HH:MM", new Date())
          console.log(date)
          wx.cloud.callFunction({
              name: 'getUserNum'
            })
            .then(res => {
              console.log(res)
              let num = res.result.total
              for (var i = 0; i <= num;) {
                wx.cloud.callFunction({
                    name: 'sendColumnPreviewMessage',
                    data: {
                      num: i,
                      time: date
                    }
                  })
                  .then(res => {
                    console.log(res)
                  })
                  .catch(err => {
                    console.log(err)
                  })
                i = i + 20
              }
              wx.showToast({
                title: '群发完成',
              })
            })
            .catch(err => {
              console.log(err)
            })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  sendVotingBeginMessage() {
    var that = this
    wx.showModal({
      confirmColor: 'red',
      title: '提示',
      content: '是否确认群发，无法撤回！',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          var date = that.dateFormat("YYYY-mm-dd HH:MM", new Date())
          console.log(date)
          wx.cloud.callFunction({
              name: 'getUserNum'
            })
            .then(res => {
              console.log(res)
              let num = res.result.total
              for (var i = 0; i <= num;) {
                wx.cloud.callFunction({
                    name: 'sendVotingBeginMessage',
                    data: {
                      num: i,
                      time: date
                    }
                  })
                  .then(res => {
                    console.log(res)
                  })
                  .catch(err => {
                    console.log(err)
                  })
                i = i + 20
              }
              wx.showToast({
                title: '群发完成',
              })
            })
            .catch(err => {
              console.log(err)
            })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  dateFormat(fmt, date) {
    let ret
    const opt = {
      "Y+": date.getFullYear().toString(), // 年
      "m+": (date.getMonth() + 1).toString(), // 月
      "d+": date.getDate().toString(), // 日
      "H+": date.getHours().toString(), // 时
      "M+": date.getMinutes().toString(), // 分
      "S+": date.getSeconds().toString() // 秒
      // 有其他格式化字符需求可以继续添加，必须转化成字符串
    }
    for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt)
      if (ret) {
        fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
      }
    }
    return fmt
  },
  onDisplay() {
    this.setData({
      show: true
    })
  },
  onClose() {
    this.setData({
      show: false
    })
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getMonth() + 1}/${date.getDate()}`;
  },
  onConfirm(event) {
    this.loadModal()
    const [start, end] = event.detail
    let that = this
    this.setData({
      show: false,
      date: `${this.formatDate(start)} - ${this.formatDate(end)}`,
    });
    var startTime = new Date(start).toLocaleDateString()
    var endTime = new Date(end).toLocaleDateString()
    wx.cloud.callFunction({
        name: 'exportSongList',
        data: {
          startTime: startTime,
          endTime: endTime
        }
      })
      .then(res => {
        console.log(res)
        that.getFileUrl(res.result.fileID)
      })
      .catch(err => {
        console.log(err)
      })
  },
  getFileUrl(fileID) {
    let that = this
    wx.cloud.getTempFileURL({
      fileList: [fileID],
      success: res => {
        console.log("文件下载链接", res.fileList[0].tempFileURL)
        this.copy(res.fileList[0].tempFileURL)
        wx.downloadFile({
          url: res.fileList[0].tempFileURL,
          success: res => {
            const filePath = res.tempFilePath
            wx.openDocument({
              filePath: filePath,
              success: res => {
                console.log('open document success')
                this.setData({
                  loadModal: false
                })
              }
            })
          }
        })
      },
      fail: err => {
        console.log(err)
      }
    })
  },
  copy(thing) {
    wx.setClipboardData({
      data: thing,
      success(res) {
        wx.getClipboardData({
          success(res) {
            console.log("复制成功", res.data)
          }
        })
      }
    })
  },
  loadModal() {
    this.setData({
      loadModal: true
    })
    setTimeout(() => {
      this.setData({
        loadModal: false
      })
    }, 700)
  }
})